package org.lonetree.tc.webapp.actions;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.lonetree.tc.core.User;

public abstract class SecureAction extends Action {

	public static final String LAST_REQUEST_TIME_IN_SESSION = "user.login.time.in.session";
	
	private User currentUser;
	
	@Override
	public final ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		HttpSession session = request.getSession();
		User currentUser = (User)session.getAttribute(LogonAction.LOGGED_IN_USER_IN_SESSION);
		java.util.Date logontime = (Date)session.getAttribute(LAST_REQUEST_TIME_IN_SESSION);
		if((currentUser != null) && !logonExpired(logontime)){
			//execute the action
			this.currentUser = currentUser;
			session.setAttribute(LAST_REQUEST_TIME_IN_SESSION, new Date());
			return executeSecure(mapping, form, request, response);
		}
		else{
			//user has not logged on (i.e. not successfully executed the /Logon.do)
			return mapping.findForward("loginPage"); //TODO edit struts-config.xml to have "loginPage" as a global forward
		}
	}
	
	private static final long LOGON_EXPIRY = 5 * 60 * 1000; //TODO tweak the logon expiry time
	
	private boolean logonExpired(java.util.Date logontime){
		return new java.util.Date().getTime() - logontime.getTime() > LOGON_EXPIRY;
	}

	protected abstract ActionForward executeSecure(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception;
	
	protected User getCurrentUser(){
		return currentUser;
	}
	
}
